package org.wisdom.data.jpa.support;

import javax.sql.DataSource;

import org.hibernate.engine.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl;
import org.wisdom.context.WisdomContextHolder;

import lombok.extern.slf4j.Slf4j;

/**
 * 这个类是Hibernate框架拦截sql语句并在执⾏sql语句之前更换数据源提供的类
 *
 * @author 张智研
 * @date 2022/05/26 13:45
 **/
@Slf4j
public class WisdomMultiTenantConnectionProviderImpl extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
    @Override
    protected DataSource selectAnyDataSource() {
        String currentTenantId = WisdomContextHolder.getContext().getTenantId();
        log.info("获取默认租户{}数据源", currentTenantId);
        return WisdomMultiTenantDataSourceProvider.getTenantDataSource(currentTenantId);
    }

    @Override
    protected DataSource selectDataSource(String tenantIdentifier) {
        log.info("获取指定租户{}数据源", tenantIdentifier);
        return WisdomMultiTenantDataSourceProvider.getTenantDataSource(tenantIdentifier);
    }
}
